<?php

namespace App\Services;

use App\Models\Crm_Wall;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class WallService
{
    public function getWallList($params)
    {
        $result = Crm_Wall::getFilter($params)
            ->Nodel()
            ->paginate($params['pageSize']);

        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }

    public function wallUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            if(!empty($params['id'])){
                $res = Crm_Wall::where('id',$params['id'])->update([
                    'title' => $params['title'],
                    'cover' => $params['cover'],
                    'status' => $params['status'],
                    'content' => $params['content'],
                    'order' => $params['order'],
                    'malename' => $params['malename'],
                    'femalename' => $params['femalename'],
                    'zans' => $params['zans']
                ]);
                if(!$res){
                    throw new \Exception("更新Crm_Wall案例失败" );
                }
            }else{
                $res = Crm_Wall::create([
                    'title' => $params['title'],
                    'cover' => $params['cover'],
                    'status' => $params['status'],
                    'content' => $params['content'],
                    'order' => $params['order'],
                    'malename' => $params['malename'],
                    'femalename' => $params['femalename'],
                    'zans' => $params['zans']
                ]);
                if(!$res){
                    throw new \Exception("新增Crm_Wall案例失败" );
                }
            }

            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function wallDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Wall::find($params['id']);
            $res->is_del = 'Y';

            if(!$res->save()){
                throw new \Exception("删除Crm_Wall案例失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

}
